<template>
  <div>
    <el-table
      :row-style="{ height: '80px' }"
      :header-row-style="{ height: '80px' }"
      :data="state.tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column fixed prop="id" label="订单编号" width="200" />
      <el-table-column prop="createTime" label="订单创建日期" width="200" />
      <el-table-column prop="state" label="订单状态" width="200"></el-table-column>

      <el-table-column prop="totalMoney" label="订单价格" width="150" />

      <el-table-column prop="sysCustomer.username" label="顾客姓名" width="200" />
      <el-table-column prop="sysCustomer.phone" label="顾客手机" width="150" />

      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <!-- <el-button link type="info" @click="showDetailPopover(scope.row.id)"
            >详情</el-button
          >
          <el-button link type="success" @click="showExaminePopover(scope.row.id)"
            >审核</el-button
          > -->
          <el-button link type="danger" @click="showDeletePopover(scope.row.id)"
            >删除</el-button
          >
          <!-- <el-button
            v-if="!scope.row.isKefu"
            link
            type="primary"
            @click="updateShopPlace(scope.row.id)"
            >修改</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="demo-pagination-block" style="margin-top: 30px">
    <el-pagination
      v-model:current-page="state.searchData.page"
      v-model:page-size="state.searchData.limit"
      :page-sizes="
        state.searchData.total <= 40
          ? [10, 20, 30, 40]
          : [10, 20, 30, 40, state.searchData.total]
      "
      :disabled="false"
      :background="true"
      layout="->,total, sizes, prev, pager, next, jumper"
      :total="state.searchData.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog v-model="examineDialogVisible" title="订单审核">
      <div style="font-size: 20px" class="mb-4">订单编号：{{ currentId }}</div>
      <div style="font-size: 20px">
        订单状态：
        <el-radio-group v-model="radio1">
          <el-radio label="审核中" border size="large">审核中</el-radio>
          <el-radio label="审核通过" border size="large">审核通过</el-radio>
          <el-radio label="审核不通过" border size="large">审核不通过</el-radio>
        </el-radio-group>
        <div style="font-size: 20px" class="mt-4" v-if="radio1 == '审核不通过'">
          <el-input
            placeholder="请填写不通过原因"
            :rows="3"
            resize="none"
            type="textarea"
            v-model="errReason"
          ></el-input>
        </div>
        <div class="mt-5 text-center">
          <el-button
            style="width: 100px; height: 40px"
            type="info"
            @click="cancalChangeState"
            >取消</el-button
          >
          <el-button
            style="width: 100px; height: 40px; margin-left: 100px"
            type="success"
            @click="confirmChangeState"
            >确定</el-button
          >
        </div>
      </div>
    </el-dialog>
    <el-dialog v-model="batchExamineDialogVisible" title="订单批量审核">
      <div style="font-size: 20px" class="mb-4">订单编号分别为：{{ ids }}</div>
      <div style="font-size: 20px">
        订单批量审核：
        <el-radio-group v-model="radio1">
          <el-radio label="审核中" border size="large">审核中</el-radio>
          <el-radio label="审核通过" border size="large">审核通过</el-radio>
          <el-radio label="审核不通过" border size="large">审核不通过</el-radio>
        </el-radio-group>
        <div style="font-size: 20px" class="mt-4" v-if="radio1 == '审核不通过'">
          <el-input
            placeholder="请填写不通过原因"
            :rows="3"
            resize="none"
            type="textarea"
            v-model="errReason"
          ></el-input>
        </div>
        <div class="mt-5 text-center">
          <el-button
            style="width: 100px; height: 40px"
            type="info"
            @click="cancalbatchChangeState"
            >取消</el-button
          >
          <el-button
            style="width: 100px; height: 40px; margin-left: 100px"
            type="success"
            @click="confirmbatchChangeState"
            >确定</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, markRaw, onBeforeMount } from "vue";
import {
  Edit,
  User,
  LocationFilled,
  Location,
  UploadFilled,
} from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage, ElLoading } from "element-plus";
import request from "../../api/request";
import router from "../../router";
const dialogFormVisible = ref(false);
const updatedialogFormVisible = ref(false);
const isShowDeletaBatchBtn = ref(true);
const drawer = ref(false);
const importDataDialogVisible = ref(false);
const examineDialogVisible = ref(false);
const batchExamineDialogVisible = ref(false);
const ids = ref([]);
const value2 = ref("");
const disabledDate = (time) => {
  return time.getTime()  > Date.now();
};
const defaultTime2 = [new Date(2023, 1, 1, 0, 0, 0), new Date(2023, 1, 1, 23, 59, 59)]; // '12:00:00', '08:00:00'
const shortcuts = [
  {
    text: "今天一天",
    value: () => {
      const end = new Date(new Date().toLocaleDateString());
      const start = new Date(new Date().toLocaleDateString());
      start.setTime(start.getTime());
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 1);
      return [start, end];
    },
  },
  {
    text: "昨天一天",
    value: () => {
      // 先得到今天的0点 
      // 昨天一天 00:00:00 => 23:59:59
      const end = new Date(new Date().toLocaleDateString());
      const start = new Date(new Date().toLocaleDateString());
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
      end.setTime(end.getTime() - 1 * 1 * 1 * 1);
      return [start, end];
    },
  },
  {
    text: "过去三天",
    value: () => {
      const end = new Date(new Date().toLocaleDateString());
      const start = new Date(new Date().toLocaleDateString());
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
      end.setTime(end.getTime() - 1 * 1 * 1 * 1);
      return [start, end];
    },
  },
  {
    text: "过去一周",
    value: () => {
      const end = new Date(new Date().toLocaleDateString());
      const start = new Date(new Date().toLocaleDateString());
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      end.setTime(end.getTime() - 1);
      return [start, end];
    },
  },
];
const props = { checkStrictly: true };
const radio1 = ref("审核通过");
const radio2 = ref("全部状态");
const defalutCity = ref([]);
const errReason = ref("");
const dialogForm = reactive({
  name: "",
  code: "",
  newProvince: "",
  newCity: "",
  newCounty: "",
});


const state = reactive({
  tableData: [],
  searchData: {
    page: 1,
    limit: 10,
  },
});
const initData = () => {
  let authentication = localStorage.getItem("adminInfo");
  if (!(authentication == 2)) {
    router.push("/admin/login");
    return;
  }
  request.post("/order/adminList", state.searchData).then((res) => {
    if (res.code == 200) {
      state.tableData = res.data.records;
      state.searchData.total = res.data.total;
    }
  });
};
initData();

const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  if (multipleSelection._rawValue.length) {
    isShowDeletaBatchBtn.value = false;
  } else {
    isShowDeletaBatchBtn.value = true;
  }
};
const showDeletePopover = (id) => {
  ElMessageBox.confirm(`您确定删除  订单编号为  ${id}  的订单吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
  })
    .then(() => {
      request.post("/order/remove" ,id).then((res) => {
        ElMessage({
          type: "success",
          message: res.msg,
        });
        if (res.code == 200) {
          initData();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
const batchDelte = () => {
  let ids = multipleSelection._rawValue.map((v) => v.id);
  ElMessageBox.confirm(`您确定删除吗`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
  })
    .then(() => {
      request.post("/order/batch/deleteOrder", ids).then((res) => {
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: res.msg,
          });
          initData();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};

const handleCurrentChange = (page) => {
  state.searchData.page = page;
  initData();
};

const handleSizeChange = (limit) => {
  state.searchData.limit = limit;
  initData();
};


const batchExport = () => {
  ElMessageBox.confirm(`您确定导出吗`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
  })
    .then(() => {
      const loading = ElLoading.service({
        lock: true,
        text: "表格导出中",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let ids = multipleSelection._rawValue.map((v) => v.id);
      let ids2 = ids.toString();
      request
        .get("/order/batch/newExportAllInfo?ids=" + ids2, {
          responseType: "blob",
        })
        .then((res) => {
          loading.close();
          const a = document.createElement("a");
          a.href = res;
          a.download = "订单信息.xlsx";
          a.click();
          a.remove();
          URL.revokeObjectURL(res);
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};

let fileList = reactive([]);
const UploadFileUrl = () => {
  // 因为action参数是必填项，我们使用二次确认进行文件上传时，
  // 直接填上传文件的url会因为没有参数导致api报404，所以这里将action设置为一个返回为空的方法就行，避免抛错
  return "";
};

// 文件超出个数限制时的钩子
const handleExceed = () => {
  ElMessage({
    type: "warning",
    message: "一次最多只能上传1个文件哦",
  });
};
//  // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const fileChange = (file, list) => {
  fileList = list;
};

const currentId = ref(0);
const showExaminePopover = (id) => {
  examineDialogVisible.value = true;
  currentId.value = id;
};
const cancalChangeState = () => {
  radio1.value = "审核通过";
  examineDialogVisible.value = false;
};
const confirmChangeState = () => {
  if (radio1.value == "审核中") {
    request.post("/order/examineOrderExamining", currentId.value).then((res) => {
      initData();
      examineDialogVisible.value = false;
    });
    return;
  }
  if (radio1.value == "审核不通过") {
    let obj = {
      id: currentId.value,
      errReason: errReason.value,
    };
    request.post("/order/examineOrderError", obj).then((res) => {
      initData();
      radio1.value = "审核通过";
      examineDialogVisible.value = false;
      errReason.value = "";
    });
    return;
  }
  if (radio1.value == "审核通过") {
    request.post("/order/examineOrderRight", currentId.value).then((res) => {
      initData();
      examineDialogVisible.value = false;
    });
    return;
  }
};
const showDetailPopover = (id) => {
  router.push("/admin/editOrderManager?params=" + id);
};
const batchExamine = () => {
  batchExamineDialogVisible.value = true;
  ids.value = multipleSelection._rawValue.map((v) => v.id);
};
const cancalbatchChangeState = () => {
  radio1.value = "审核通过";
  batchExamineDialogVisible.value = false;
};
const confirmbatchChangeState = () => {
  // console.log(ids.value);
  // console.log(radio1.value);
  // console.log(errReason.value);
  let obj = {
    ids: ids.value,
    state: radio1.value,
    errReason: errReason.value,
  };
  request.post("/order/batch/examineOrder", obj).then((res) => {
    if (res.code == 200) {
      // ElMessage({
      //   type: "success",
      //   message: "批量修改成功",
      // });
      initData();
      radio1.value = "审核通过";
      errReason.value = "";
      batchExamineDialogVisible.value = false;
    }
  });
};
const startChangeSearch = () => {
 
  if(radio2.value == "全部状态"){
    state.searchData.state = ''
  }else{
    state.searchData.state = radio2.value
  }
  if (value2.value != null) {
    state.searchData.startTime = value2.value[0];
    state.searchData.endTime = value2.value[1];
    initData();
  } else {
    initData();
  }
};
</script>
<style lang="scss"></style>
